package 剑指offer;

/**
 * @description:
 * @author: ywk
 * @date: 2021-03-13
 */
public class 子集背包问题 {
    public static boolean canPartition(int[] nums) {
        int sum = 0, n = nums.length;
        for (int num : nums) {
            sum += num;
        }
        if (sum % 2 != 0) {
            return false;
        }
        sum = sum / 2;
        boolean[][] dp = new boolean[sum + 1][sum + 1];
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = true;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                if (j - nums[i - 1] < 0) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = dp[i - 1][j] | dp[i - 1][j - nums[i - 1]];
                }
            }
        }
        return dp[n][sum];
    }

    //从二维数组转为一维数组，进行状态压缩
    public static boolean canPartitionCompress(int[] nums) {
        int sum = 0, n = nums.length;
        for (int num : nums) {
            sum += num;
        }
        if (sum % 2 != 0) {
            return false;
        }
        sum = sum / 2;
        boolean[] dp = new boolean[sum + 1];
        dp[0] = true;
        for (int i = 1; i <= n; i++) {
            for (int j = sum; j >= 0; j--) {
                if (j - nums[i - 1] > 0) {
                    dp[j] = dp[j] | dp[j - nums[i - 1]];
                }
            }
        }
        return dp[sum];
    }

    public static void main(String[] args) {
        System.out.println(canPartition(new int[]{1, 3, 4, 4}));
        System.out.println(canPartitionCompress(new int[]{1, 3, 4, 4}));
    }
}